﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSBTC.Model;

namespace MSBTC.WinForms
{
    public partial class DeliveryReceiptForm : Form
    {
        MDIParent mdipar = new MDIParent();
        private string Datamanip;
        PMSContext dbcontext = new PMSContext();
        DeliveryReceipt dbDR = new DeliveryReceipt();
        MaterialsInventory dbmat = new MaterialsInventory();
        FormHelpers help = new FormHelpers();
        ProjMat dbpm = new ProjMat();

        private int rowselect;

        public DeliveryReceiptForm()
        {
            InitializeComponent();
        }       

        private void DeliveryReceiptForm_Load(object sender, EventArgs e)
        {
            RefreshDB();
            RefreshFields();

            var por = (from p in dbcontext.PurchOrder
                       select p).ToList();
            if (por != null)
            {
                foreach (var itm in por)
                {
                    cmbPO.Items.Add(itm.POnum.ToString());
                }
            }
            else
            {
                MessageBox.Show("There are no Purchase order yet, please create a requisition then create purchase order", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

           
            
        }

        #region Functions
        private void RefreshDB()
        {
           
            //retrieve all data of projects in List
            var DR = (from c in dbcontext.DeliveryReceipts
                      select c).ToList();

            LVDRInfo.Items.Clear();
            if (DR.Count != 0)
            {
                foreach (var sqlDR in DR)
                {
                    //add items in listview box
                    ListViewItem lvitems = LVDRInfo.Items.Add(sqlDR.DRid_PK.ToString());
                    lvitems.SubItems.Add(sqlDR.InvoiceNo.ToString());
                    lvitems.SubItems.Add(sqlDR.Receivedby.ToString());
                    lvitems.SubItems.Add(sqlDR.DateTransact.ToString());

                    var po = dbcontext.PurchOrder.Find(sqlDR.poid_FK);
                    lvitems.SubItems.Add(po.POnum.ToString());
                    lvitems.SubItems.Add(sqlDR.status.ToString());

                }
            }
        }

        private void ClearFields()
        {
            txtInv.Clear();
            txtRecby.Clear();
            txtDate.Clear();
            cmbPO.SelectedIndex = 0;
            cmbStat.SelectedIndex = 0;
            txtID.Clear();
            txtSearch.Clear();
            

        }

        private void DisableFields()
        {
            txtInv.Enabled = false;
            txtRecby.Enabled = false;
            txtDate.Enabled = false;
            cmbPO.Enabled = false;
            cmbStat.Enabled = false;

        }

        private void EnableFields()
        {
            txtInv.Enabled =true;
            txtRecby.Enabled = true;
            txtDate.Enabled = true;
            cmbPO.Enabled = true;
            cmbStat.Enabled = true;
        }

        private void RefreshFields()
        {
            DisableFields();
            ClearFields();
            LVDRInfo.Enabled = true;
            btnNew.Enabled = true;
            btnDel.Enabled = false;
            btnEdit.Enabled = false;
            btnClear.Enabled = true;
            btnSave.Enabled = false;
        }
        #endregion

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearFields();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {

            Datamanip = "Add";

            EnableFields();
            ClearFields();

            btnSave.Enabled = true;
            btnNew.Enabled = false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Datamanip = "Edit";

            EnableFields();

            btnSave.Enabled = true;
            btnNew.Enabled = false;
            btnDel.Enabled = false;
            btnEdit.Enabled = false;
            LVDRInfo.Enabled = false;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshFields();
            
        }

        #region Save
        private void btnSave_Click(object sender, EventArgs e)
        {
            if ((txtInv.Text == null) || (txtRecby.Text == null) || (txtDate == null))
            {
                MessageBox.Show("Please fill up the missing fields", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if ((cmbPO.SelectedIndex == 0) || (cmbStat.SelectedIndex==0))
            {
                MessageBox.Show("Please select supplier name", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (help.SpecChar(txtInv.Text, txtInv) == false || help.SpecChar(txtRecby.Text, txtRecby) == false)
            {
                MessageBox.Show("Special Characters are not allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {

                if (Datamanip == "Add")
                {

                    int inv = Convert.ToInt32(txtInv.Text);
                    var poid = (from po in dbcontext.PurchOrder
                                where po.POnum == cmbPO.SelectedItem
                                select po).DefaultIfEmpty().SingleOrDefault();

                    var add = (from p in dbcontext.DeliveryReceipts
                               where p.InvoiceNo == inv && p.poid_FK == poid.poid_PK
                               select p).SingleOrDefault();

                    if (add == null)
                    {
                        dbDR.InvoiceNo = inv;
                        dbDR.DateTransact = txtDate.Text;
                        dbDR.Receivedby = txtRecby.Text;

                        var po = (from p in dbcontext.PurchOrder
                                  where p.POnum == cmbPO.SelectedItem
                                  select p).SingleOrDefault();
                        if (po != null)
                        {
                            dbDR.poid_FK = po.poid_PK;
                        }
                        dbDR.status = cmbStat.Text;

                        dbcontext.Entry(dbDR).State = EntityState.Added;
                        dbcontext.SaveChanges();
                        SaveAll();

                        MessageBox.Show("Successfully Saved", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        RefreshFields();
                        RefreshDB();
                        
                    }
                    else
                    {
                        DialogResult YN = MessageBox.Show("Invoice already exist, do you want to replace it?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (YN == DialogResult.Yes)
                        {
                            var replace = dbcontext.DeliveryReceipts.Find(add.DRid_PK);
                           
                            replace.InvoiceNo = Convert.ToInt32(txtInv.Text);
                            replace.Receivedby = txtRecby.Text;
                            replace.DateTransact = txtDate.Text;                                              

                            var por = (from p in dbcontext.PurchOrder
                                        where p.POnum == cmbPO.SelectedItem
                                        select p).SingleOrDefault();
                            replace.poid_FK = por.poid_PK;
                            replace.status = cmbStat.Text;

                            dbcontext.Entry(replace).State = EntityState.Modified;
                            dbcontext.SaveChanges();
                            SaveAll();

                            MessageBox.Show("Successfully Modified", "Modify", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            RefreshFields();
                            RefreshDB();
                        }
                    }
                    LVDRInfo.Enabled = true;
                }
                else if (Datamanip == "Edit")
                {
                    txtInv.Enabled = false;
                    DialogResult YN = MessageBox.Show("Invoice already exist, Do you want to replace it?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (YN == DialogResult.Yes)
                    {
                        var replace = dbcontext.DeliveryReceipts.Find(Convert.ToInt32(txtID.Text));
                           
                            replace.InvoiceNo = Convert.ToInt32(txtInv.Text);
                            replace.Receivedby = txtRecby.Text;
                            replace.DateTransact = txtDate.Text;
                                           

                            var por = (from p in dbcontext.PurchOrder
                                        where p.POnum == cmbPO.SelectedItem
                                        select p).SingleOrDefault();
                            replace.poid_FK = por.poid_PK;
                            replace.status = cmbStat.Text;  

                            dbcontext.Entry(replace).State = EntityState.Modified;
                            dbcontext.SaveChanges();
                                
                            MessageBox.Show("Successfully Modified", "Modify", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            RefreshFields();
                            RefreshDB();
                    }
                }

            }
        }
        #endregion

        private void btnDel_Click(object sender, EventArgs e)
        {
            DialogResult YN = MessageBox.Show("Do you want to Delete selected invoice?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (YN == DialogResult.Yes)
            {
                var del = dbcontext.DeliveryReceipts.Find(Convert.ToInt32(txtID.Text));//get the same ID of purchase order to delete
                if (del != null)
                {
                    //delete the ID selected
                    dbcontext.Entry(del).State = EntityState.Deleted;
                    dbcontext.SaveChanges();
                }
                RefreshFields();
                RefreshDB();
            }
        }

        private void LVDRInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //focus the selected items
            rowselect = LVDRInfo.FocusedItem.Index;

            //getting the information from the listview to textbox
            txtID.Text = LVDRInfo.Items[rowselect].SubItems[0].Text;
            txtInv.Text = LVDRInfo.Items[rowselect].SubItems[1].Text;
            txtRecby.Text = LVDRInfo.Items[rowselect].SubItems[2].Text;
            txtDate.Text = LVDRInfo.Items[rowselect].SubItems[3].Text;
            cmbPO.SelectedItem = LVDRInfo.Items[rowselect].SubItems[4].Text;
            cmbStat.SelectedItem = LVDRInfo.Items[rowselect].SubItems[5].Text;

            btnDel.Enabled = true;
            btnEdit.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = false;

        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtSearch.Text == "")
            {
                RefreshDB();
            }
            else
            {
                //retrieve the same item name search by user
                var src = Convert.ToInt32(txtSearch.Text);
                var purch = (from p in dbcontext.DeliveryReceipts
                             where p.InvoiceNo == src
                             select p).ToList();

                LVDRInfo.Items.Clear();
                if (purch.Count != 0)
                {
                    foreach (var sqlCus in purch)
                    {
                        ListViewItem lvitems = LVDRInfo.Items.Add(sqlCus.DRid_PK.ToString());
                        lvitems.SubItems.Add(sqlCus.InvoiceNo.ToString());
                        lvitems.SubItems.Add(sqlCus.Receivedby.ToString());
                        lvitems.SubItems.Add(sqlCus.DateTransact.ToString());
                           
                        var po = dbcontext.PurchOrder.Find(sqlCus.poid_FK);
                        lvitems.SubItems.Add(po.POnum.ToString());
                        lvitems.SubItems.Add(sqlCus.status.ToString());

                    }

                }

            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbPO_SelectedIndexChanged(object sender, EventArgs e)
        {
            //var po = (from p in dbcontext.PurchOrder
            //          where p.POnum == cmbPO.SelectedItem
            //          select p).SingleOrDefault();
            //if (po != null)
            //{
            //    var proj = dbcontext.Projects.Find(po.Projectid_FK);
            //    ListViewItem lvitems = LVPO.Items.Add(proj.Project_Name.ToString());
            //    lvitems.SubItems.Add(po.Requisitionid.ToString());
            if (cmbPO.SelectedIndex == 0)
            {
                return;
            }
            var po = (from p in dbcontext.PurchOrder
                      where p.POnum == cmbPO.SelectedItem
                      select p).SingleOrDefault();

            var reqid = (from p in dbcontext.Requests
                         where p.Requisitionid == po.Requisitionid
                         select p).ToList();


            LVD.Items.Clear();
            if (reqid != null)
            {
            //    var req = (from r in dbcontext.Requests
            //               where r.Requisitionid == po.Requisitionid
            //               select r).ToList();
            //    if (req.Count != 0)
            //    {
            //        foreach (var itm in req)
            //        {
            //            var sup = (from s in dbcontext.Suppliers
            //                       where s.Supplierid_PK == itm.Supplierid_FK
            //                       select s).SingleOrDefault();
            //            if (sup != null)
            //            {
            //                lvitems.SubItems.Add(sup.Supplier_Name.ToString());
            //            }
            //        }
            //    }
        
                foreach (var sqlCus in reqid)
                {
                    ListViewItem lvitems = LVD.Items.Add(sqlCus.MaterialName.ToString());
                    lvitems.SubItems.Add(sqlCus.Quantity.ToString());
                    lvitems.SubItems.Add(sqlCus.Unit.ToString());
                  
                }
            }            
            //}
        }

        private void SaveAll()
        {
            
            var por = (from p in dbcontext.PurchOrder
                       where p.POnum == cmbPO.SelectedItem
                       select p).SingleOrDefault();
            if(por != null)
            {
                var req = (from r in dbcontext.Requests
                           where r.Requisitionid == por.Requisitionid
                           select r).ToList();
                if(req.Count != 0)
                {
                    foreach (var rq in req)
                    {
                        var mat = (from m in dbcontext.MaterialsInventorys
                                   where m.Material_Name.ToLower().Trim() == rq.MaterialName.ToLower().Trim()
                                   select m).SingleOrDefault();
                        if (mat == null)
                        {
                            dbmat.Material_Name = rq.MaterialName;
                            dbmat.Qty = rq.Quantity;
                            dbmat.QtyUsed = rq.Quantity;
                            dbmat.Unit = rq.Unit;
                            dbmat.UnitCost = rq.UnitCost;

                            dbcontext.Entry(dbmat).State = EntityState.Added;
                            dbcontext.SaveChanges();

                            //var mtr = (from m in dbcontext.MaterialsInventorys
                            //           where m.Material_Name.ToLower().Trim() == rq.MaterialName.ToLower().Trim()
                            //           select m).SingleOrDefault();
                            //if (mtr != null)
                            //{
                            //    var pjmat = (from pm in dbcontext.PrjMatls
                            //                 where pm.MaterialsInventoryid_FK == mat.MaterialsInventoryid_PK &&
                            //                 pm.Projectid_FK == por.Projectid_FK
                            //                 select pm).ToList();
                            //    if (pjmat.Count == 0)
                            //    {
                            //        dbpm.MaterialsInventoryid_FK = mtr.MaterialsInventoryid_PK;
                            //        dbpm.Projectid_FK = por.Projectid_FK;
                            //        dbpm.QtyUsed = rq.Quantity;

                            //        dbcontext.Entry(dbpm).State = EntityState.Added;
                            //        dbcontext.SaveChanges();
                            //    }
                            //    else
                            //    {
                            //        foreach (var itm in pjmat)
                            //        {
                            //            itm.QtyUsed += rq.Quantity;

                            //            dbcontext.Entry(itm).State = EntityState.Modified;
                            //            dbcontext.SaveChanges();
                            //        }
                            //    }
                            //}
                        }
                        else
                        {
                            mat.Qty += rq.Quantity;
                            mat.QtyUsed += rq.Quantity;
                            mat.UnitCost += rq.UnitCost;

                            dbcontext.Entry(mat).State = EntityState.Modified;
                            dbcontext.SaveChanges();

                            //var pjmat = (from pm in dbcontext.PrjMatls
                            //             where pm.MaterialsInventoryid_FK == mat.MaterialsInventoryid_PK &&
                            //             pm.Projectid_FK == por.Projectid_FK
                            //             select pm).ToList();
                            //if (pjmat.Count == 0)
                            //{
                            //    dbpm.MaterialsInventoryid_FK = mat.MaterialsInventoryid_PK;
                            //    dbpm.Projectid_FK = por.Projectid_FK;
                            //    dbpm.QtyUsed = rq.Quantity;

                            //    dbcontext.Entry(dbpm).State = EntityState.Added;
                            //    dbcontext.SaveChanges();
                            //}
                            //else
                            //{
                            //    foreach (var itm in pjmat)
                            //    {
                            //        itm.QtyUsed += rq.Quantity;

                            //        dbcontext.Entry(itm).State = EntityState.Modified;
                            //        dbcontext.SaveChanges();
                            //    }
                            //}
                        }

                        
                    }
                }
            }
             
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

   }
        
}
